<script setup>
import { ref, onMounted, computed } from 'vue'
import { sessionApi, pageConfsApi, saveConfApi, oneConfApi, proConfsApi } from '@/commons/api'
import routes from '@/commons/router'
import Msg from '@/components/message'
import Confirm from '@/components/confirm'
import Pager from '@/components/pager/Pager.vue'
import { CScrollbar } from 'c-scrollbar'
import Loader from '@/components/loader/Loader.vue'

const loadShow = ref(false)

// 界面挂载前处理
onMounted(() => {
  // 获取用户会话信息
  checkAuth()
})

let procAuth = {
  addAuth: false,
  delAuth: false,
  edtAuth: false,
  pasAuth: false,
  unpAuth: false
}
// checkAuth 获取权限
const checkAuth = async () => {
  loadShow.value = true
  try {
    const res = await sessionApi()
    if (res.code === import.meta.env.VITE_SUCCESS_CODE) {
      const userBtnCode = res.data.btnCodes
      procAuth = {
        addAuth: userBtnCode.indexOf('1001010101') !== -1,
        delAuth: userBtnCode.indexOf('1001010102') !== -1,
        edtAuth: userBtnCode.indexOf('1001010103') !== -1,
        pasAuth: userBtnCode.indexOf('1001010104') !== -1,
        unpAuth: userBtnCode.indexOf('1001010105') !== -1
      }
      await list(0, 1)
    } else {
      localStorage.removeItem("token")
      Msg({ kind: 'error', txt: res.msg })
      routes.replace('/login')
    }
    loadShow.value = false
  } catch (e) {
    loadShow.value = false
    Msg({ kind: 'error', txt: '系统错误，请联系管理员！' + e })
  }
}

const schRef = ref({
  keywords: '',
  offset: 0,
  limit: 20
})
const total = ref(0)
const curPage = ref(1)
const confList = ref([])
const hasData = ref(false)
// list 列表展示
const list = async (offset, cur) => {
  schRef.value.offset = offset || 0
  curPage.value = cur || 1
  hasData.value = false
  const res = await pageConfsApi(schRef.value)
  if(res.code === import.meta.env.VITE_SUCCESS_CODE && res.data) {
    hasData.value = true
    total.value = res.data.total
    confList.value = res.data.list
    idList.value = []
    checkList.value = []
    allCheck.value = false
    res.data.list.forEach(() => {
      checkList.value.push(false)
    })
  }
}

// search 筛选
const schShow = ref(false)
const search = () => {
  schShow.value = !schShow.value
}

// clrSch 重置搜索框
const clrSch = () => {
  schRef.value = {
    keywords: '',
    offset: 0,
    limit: 20
  }
  list(0, 1)
}

// 选择效果实现
const idList = ref([])
const checkList = ref([])
const allCheck = ref(false)
// checkAll 全选
const checkAll = () => {
  idList.value = []
  checkList.value = []
  allCheck.value = !allCheck.value
  if(allCheck.value) {
    confList.value.forEach(item => {
      idList.value.push(item.confId)
      checkList.value.push(true)
    })
  } else {
    confList.value.forEach(() => {
      checkList.value.push(false)
    })
  }
}
// checkCurId 单选
const checkCurId = (idx, roleId) => {
  if(!checkList.value[idx]) {
    idList.value.push(roleId)
  } else {
    idList.value.splice(idList.value.findIndex(id => id === roleId), 1)
  }
  checkList.value[idx] = !checkList.value[idx]
}

const confForm = ref({
  confId: '',
  confType: '',
  confName: '',
  confKey: '',
  confVal: '',
  remarks: ''
})
// add 新增
const showModal = ref(false)
const add = () => {
  showModal.value = true
}
// update 修改
const update = async (confId) => {
  loadShow.value = true
  try {
    const res = await oneConfApi({ confId })
    if(res.code === import.meta.env.VITE_SUCCESS_CODE) {
      showModal.value = true
      confForm.value = res.data
    } else {
      Msg({ kind: 'info', txt: '暂无内容' })
    }
    loadShow.value = false
  } catch(e) {
    loadShow.value = false
    Msg({ kind: 'error', txt: '系统异常，请联系管理员！' + e })
  }
}
// save 保存提交
const save = async () => {
  let confType = confForm.value.confType
  let confName = confForm.value.confName
  let confKey = confForm.value.confKey
  let confVal = confForm.value.confVal
  if(confType === '' || confType.length > 30) {
    Msg({ kind: 'warn', txt: '配置类型不能为空，且长度为30位的编码！' })
    return
  } else if(confName === '' || confName.length > 50) {
    Msg({ kind: 'warn', txt: '配置名称不能为空，且长度不超过50个字符！' })
    return
  } else if(confKey === '' || confKey.length > 50) {
    Msg({ kind: 'warn', txt: '配置键名不能为空，且长度不超过50个字符！' })
    return
  } else if(confVal === '' || confVal.length > 50) {
    Msg({ kind: 'warn', txt: '配置键值不能为空，且长度不超过50个字符！' })
    return
  }
  loadShow.value = true
  try {
    const res = await saveConfApi(confForm.value)
    if(res.code === import.meta.env.VITE_SUCCESS_CODE) {
      closeModal()
      await list(0, 1)
      Msg({ kind: 'success', txt: '恭喜您，配置信息保存成功！' })
    } else {
      Msg({ kind: 'error', txt: res.msg })
    }
    loadShow.value = false
  } catch(e) {
    loadShow.value = false
    Msg({ kind: 'error', txt: '系统异常，请联系管理员！' + e })
  }
}

// closeModal 关闭弹出层，并重置表单数据
const closeModal = () => {
  showModal.value = false
  confForm.value = {
    confId: '',
    confType: '',
    confName: '',
    confKey: '',
    confVal: '',
    remarks: ''
  }
}

// process 删除配置
const process = (states) => {
  if(!idList || idList.value.length===0) {
    Msg({ kind: 'warn', txt: '请至少选择一项再操作处理！' })
    return
  }
  Confirm('确定要处理选中的数据吗？').then(() => {
    proConfs(states)
  }).catch(() => {
    Msg({ kind: 'info', txt: "您取消了处理选中数据的操作~！" })
  })
}
// proConfs 删除配置实现，分离出来防止调用时异步报错
const proConfs = async (states) => {
  let confIds = idList.value.join(',')
  loadShow.value = true
  try {
    const res = await proConfsApi({ states, confIds })
    if(res.code === import.meta.env.VITE_SUCCESS_CODE) {
      await list(0, 1)
      Msg({ kind: 'success', txt: '恭喜您，配置信息处理成功！' })
    } else {
      Msg({ kind: 'error', txt: res.msg })
    }
    loadShow.value = false
  } catch(e) {
    loadShow.value = false
    Msg({ kind: 'error', txt: '系统异常，请联系管理员！' + e })
  }
}

// fmtState 状态转码
const fmtState = computed(() => {
  return (states) => {
    let str
    switch (states) {
      case 1:
        str = '已启用'
        break;
      case 3:
        str = '已停用'
        break;
      default:
        str = '其它'
        break
    }
    return str
  }
})
</script>

<template>
  <div class="a">
    <div class="b">
      <div class="c">
        <div v-if="procAuth.addAuth" class="btn-pi mr15" title="新增" @click="add"><i class="iconfont">&#xea2d;</i> 新增</div>
        <div v-if="procAuth.delAuth" class="btn-de mr15" title="删除" @click="process(2)"><i class="iconfont">&#xea45;</i> 删除</div>
        <div v-if="procAuth.pasAuth" class="btn-ds mr15" title="启用" @click="process(1)"><i class="iconfont">&#xea30;</i> 启用</div>
        <div v-if="procAuth.unpAuth" class="btn-dw mr15" title="停用" @click="process(3)"><i class="iconfont">&#xea2e;</i> 停用</div>
        <div class="btn-r mr15" title="筛选" @click="search"><i class="iconfont">&#xea49;</i></div>
        <div class="btn-r mr15" title="刷新" @click="list(0, 1)"><i class="iconfont">&#xea8c;</i></div>
      </div>
      <div class="d"><i class="iconfont">&#xeaaa;</i> 当前位置：工作台 > 系统管理 > 全局配置</div>
    </div>
    <div v-show="schShow" class="e">
      <div class="mr15 mt10"><input type="text" v-model="schRef.keywords" maxlength="30" placeholder="请输入关键字" class="sch-ipt" /></div>
      <div class="f mt10">
        <div class="btn-pi mr15" title="搜索" @click="list(0, 1)"><i class="iconfont">&#xea8e;</i> 搜索</div>
        <div class="btn-d" title="重置" @click="clrSch"><i class="iconfont">&#xea4f;</i> 重置</div>
      </div>
    </div>
    <div v-if="hasData">
      <table>
        <tbody>
          <tr>
            <th style="width: 5%;"><span @click="checkAll()" title="全选"><i :class="['iconfont', allCheck ? 'chked' : 'chk']" v-html="allCheck ? '&#xea3a;' : '&#xea46;'" /></span></th>
            <th style="width: 20%;">类型</th>
            <th style="width: 20%;">名称</th>
            <th style="width: 15%;">键名</th>
            <th style="width: 20%;">键值</th>
            <th style="width: 10%;">状态</th>
            <th style="width: 10%;">操作</th>
          </tr>
          <tr v-for="(curConf, index) in confList" :key="curConf.confId" class="tr-style">
            <td class="txt-center"><span @click="checkCurId(index, curConf.confId)" title="选择"><i :class="['iconfont', checkList[index] ? 'chked' : 'chk']" v-html="checkList[index]  ? '&#xe685;' : '&#xe686;'" /></span></td>
            <td class="txt-center">{{curConf.confType}}</td>
            <td class="txt-center">{{curConf.confName}}</td>
            <td class="txt-center">{{curConf.confKey}}</td>
            <td class="txt-center">{{curConf.confVal}}</td>
            <td class="txt-center"><span :class="[curConf.states===1 ? 'tag-s' : 'tag-e']">{{fmtState(curConf.states)}}</span></td>
            <td class="txt-center">
              <span v-if="procAuth.edtAuth" class="cl-warn" title="修改" @click="update(curConf.confId)"><i class="iconfont">&#xea48;</i> 修 改</span>
            </td>
          </tr>
        </tbody>
      </table>
      <pager v-if="hasData" :limit="schRef.limit" :total="total" :page="curPage" @turn="list" />
    </div>
    <div v-else class="no-data">暂无内容</div>

    <!-- 新增、修改弹出层 -->
    <transition name="fade-mod" appear>
      <div v-if="showModal" class="modal-backdrop">
        <c-scrollbar>
          <div class="modal" style="width: 600px;">
            <div class="modal-header">
              <div class="header-left"><i class="iconfont">&#xea54;</i> 保存全局配置信息</div>
              <div class="header-right" @click="closeModal()"><i class="iconfont fs22">&#xea7f;</i></div>
            </div>
            <div class="modal-body">
              <div>
                <div class="ipt-title"><span class="required">*</span>配置类型</div>
                <div><input type="text" v-model="confForm.confType" maxlength="10" placeholder="请输入配置类型" class="ipt" /></div>
              </div>
              <div>
                <div class="ipt-title"><span class="required">*</span>配置名称</div>
                <div><input type="text" v-model="confForm.confName" maxlength="50" placeholder="请输入配置名称" class="ipt" /></div>
              </div>
              <div>
                <div class="ipt-title"><span class="required">*</span>配置键名</div>
                <div><input type="text" v-model="confForm.confKey" maxlength="50" placeholder="请输入配置键名" class="ipt" /></div>
              </div>
              <div>
                <div class="ipt-title"><span class="required">*</span>配置键值</div>
                <div><input type="text" v-model="confForm.confVal" maxlength="11" placeholder="请输入配置键值" class="ipt" /></div>
              </div>
              <div>
                <div class="ipt-title">备注说明</div>
                <div><textarea v-model="confForm.remarks" class="desc-txt"></textarea></div>
              </div>
            </div>
            <div class="modal-footer">
              <div class="btn-pi mr15" @click="save"><i class="iconfont">&#xea90;</i> 保存</div>
              <div class="btn-d" @click="closeModal"><i class="iconfont">&#xea4f;</i> 取消</div>
            </div>
          </div>
        </c-scrollbar>
      </div>
    </transition>
    <loader :loadShow="loadShow" />
  </div>
</template>

<style scoped>
.a {padding: 10px;}
.b {padding: 0 20px 10px 20px; display: flex; display: -webkit-flex;}
.c {display: inline-flex; display: -webkit-inline-flex;}
.d {flex-grow: 1; text-align: right; padding-top: 10px; color: #666;}
.e {border: 1px dashed #DDD; padding: 5px 15px 15px 15px; display: flex; display: -webkit-flex; flex-wrap: wrap; margin-bottom: 10px;}
.f {display: inline-flex; display: -webkit-inline-flex;}
</style>